<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Crypt;


class LoginController extends Controller
{
    // login
    public function login()
    {
        return view('admin.login.login');
    }

    // dologin
    public function dologin(Request $request)
    {
        // dd($request);     

        // 判断验证码是否正确
        if(session('milkcaptcha') != $request -> input('code'))
        {
            return back() -> with(['info' => '验证码错误']);
        }

        $res = DB::table('user') -> where('name', $request -> input('name')) -> first();

        if($res -> status == '1')
        {
          // 验证
            $this->validate($request, [
                'name' => 'required|max:18',
                'password' => 'required|alpha_dash|max:12',
            ],[
                'name.required' => '用户名不能为空',
                'name.max' => '用户名不能大于18位',
                'password.max' => '密码不能大于12位',
                'password.required' => '密码不能为空',
                'password.alpha_dash' => '密码不合法,密码格式只能包含数字字母下划线',

            ]); 

            // 解密
            // $password = Crypt::decrypt($res -> password);
            $password = $res -> password;
            if($password != $request -> input('password'))
            {
                return back() -> with(['info' => '管理员账号或密码错误']);
            }


            session(['master' => $res]);

            return redirect('/admin/index') -> with(['info' => '登录后台页面成功']);

        }else
        {
            return back() -> with(['info' => '您的账户已经被禁用']);
        }
    }


    // logout
    public function logout()
    {
        session() -> forget('master');
        return redirect('/admin/login') -> with(['info' => '您已经退出登录!']);
    }
}
